package SedCommand;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class SedTask extends Task {

    private String sourceText;

    private String replaceText;

    private File jtlFile;

    public void setSourceText(String sourceText) {
        this.sourceText = sourceText;
    }

    public void setReplaceText(String replaceText) {
        this.replaceText = replaceText;
    }

    public void setJtlFile(File jtlFile) {
        this.jtlFile = jtlFile;
    }

    // 检查配置
    public void validitySetting(){
        if (this.sourceText == null || this.sourceText.isEmpty()) {
            throw new BuildException("sourceText name is empty");
        }
    }

    @Override
    public void execute() throws BuildException {
        this.validitySetting();
        log("Message: " + "Parameter sourceText is " + this.sourceText, Project.MSG_INFO);
        log("Message: " + "Parameter replaceText is " + this.replaceText, Project.MSG_INFO);
        log("Message: " + "SedTask Processing File " + this.jtlFile.getName(), Project.MSG_INFO);
        try {
            this.modifyFileContent(this.sourceText, this.replaceText, this.jtlFile);
        } catch (IOException e) {
            log("Message: " + "SedTask Processing File Raise Exception ", Project.MSG_ERR);
            e.printStackTrace();
        }
    }

//    public void modifyFileContent(String src, String rep, File file) throws IOException {
//        BufferedReader br = null;
//        CharArrayWriter tempStream = null;
//        OutputStreamWriter osr = null;
//        try {
//            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
//            br = new BufferedReader(isr);
//            // 内存流, 作为临时流
//            tempStream = new CharArrayWriter();
//            String line = null;
//            while ((line = br.readLine()) != null) {
//                // 替换每行中, 符合条件的字符串
//                line = line.replaceAll(src, rep);
//                // 将该行写入内存
//                tempStream.write(line);
//                // 添加换行符
//                tempStream.append(System.getProperty("line.separator"));
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//        } finally {
//            if (br != null){
//                try {
//                    br.close();
//                } catch (IOException e){
//                    br = null;
//                }
//            }
//        }
////        System.out.println(tempStream.toString());
//        // 重写入原文件
//        try{
//            osr = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
//            tempStream.writeTo(osr);
//        } catch (IOException e){
//            e.printStackTrace();
//        } finally {
//            if (osr != null){
//                try{
//                    osr.close();
//                } catch (Exception e){
//                    osr = null;
//                }
//            }
//        }
//    }

    public void modifyFileContent(String src, String rep, File file) throws IOException {

        File tmpFile = new File(file.getParentFile(), "tmp.file");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 对每行替换后直接写入目标文件
                writer.write(line.replaceAll(src, rep));
                writer.newLine();  // 添加换行符
            }
        }

        // 最后替换原文件
        Files.move(tmpFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    // bugfix 修复指定buffer大小，导致在解析buffer临界位置出现要替换字符时无法处理
//    public void modifyFileContent(String src, String rep, File file) throws IOException {
//
//        RandomAccessFile srcRAFile = new RandomAccessFile(file, "r");
//        File tmpFile = new File(file.getParentFile().getAbsolutePath(),"tmp.file");
//        RandomAccessFile tmpRAFile = new RandomAccessFile(tmpFile, "rw");
//
//        byte[] buffer = new byte[1024 * 1024];
//        int len;
//
//        while((len = srcRAFile.read(buffer)) > 0) {
//            String content = new String(buffer, 0, len, StandardCharsets.UTF_8);
//            // 替换每行中, 符合条件的字符串
//            content = content.replaceAll(src, rep);
//            buffer = content.getBytes(StandardCharsets.UTF_8);
//
//            tmpRAFile.write(buffer);
//        }
//
//        srcRAFile.close();
//        tmpRAFile.close();
//
//        Files.move(Paths.get(tmpFile.getAbsolutePath()), Paths.get(file.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
//    }

    public static void main(String[] args) throws IOException {
        new SedTask().modifyFileContent("#", "\\$", new File("C:\\demo.txt"));
    }
}
